#!/usr/bin/perl -w
#
# Show full processlit  to get query statments with long execution time
# @param $1 install home
# @param $2 pattern
# @param $3 delimiter
# @param $4 host
# @param $5 port
# @param $6 username
# @param $7 password
# -- Modify  2009.08.10  -return $exec_time  is number type
# -- Modify  2009.08.04  -filter out lockwait,flush table etc.
# -- Modify  2009.05.26  -add filter slave status and  split host 
# -- Created 2009.05.25 by DavidLi

use strict;
my $SQL="show full processlist";
my ($MYSQL_HOME,$RE,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;
my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");

my $MYSQL= defined ($MYSQL_HOME) ? "$MYSQL_HOME/bin/mysql" : "mysql";
my $MYSQLADMIN= defined $MYSQL_HOME ? "$MYSQL_HOME/bin/mysqladmin" : "mysqladmin";
if ($^O =~ m/MSWin32/) {
  $MYSQL =~ s/\//\\/g;
  $MYSQLADMIN =~ s/\//\\/g;
}

### Check if mysqld is alive
my $retmsg=`$MYSQLADMIN $PARAM ping 2>&1`;
chomp($retmsg);
if ( "$retmsg" ne "mysqld is alive" ) {
    print "em_error=Status${DELIM}Down\n";
    exit 1;
}


my @lines=`$MYSQL -N -s $PARAM --batch  -e"$SQL"`;

my $host_ip = "";
foreach my $line (@lines) {
  my $str="";
  chomp $line;
  my @row = split(/\t/,$line);
  my $id           = $row[0];
  my $user         = $row[1];
  my $host         = $row[2];
  my $db           = defined($row[3]) ? "$row[3]" : "NULL";
  my $command      = $row[4];
  my $exec_time    = $row[5];
  my $state        = $row[6];
  my $stmt         = defined($row[7]) ? "$row[7]" : "NULL";

  my $filter_text="";
  my $filter_string="system user,Connect|Binlog Dump|Sleep|lock|flushing tables|waiting for table";
  $filter_text=join(",",$user,$command,$state);

  ## filter  processes without replication ,Sleep and lock state
  if ($filter_text !~ /$filter_string/ims && $exec_time =~ /\A\d+\z/ ) {
    
    #split host field to get host ip
    if ($row[2] =~ /:/) {
       $host_ip = substr($host,0,index($host,":"));
    } 
    else {
       $host_ip = $host;
    }
 
  ##                Id|Time      |User |Host    |db |Command |State |info
  print "em_result=$id|$exec_time|$user|$host_ip|$db|$command|$state|$stmt\n"
 }
}
